//
//  FujinYDViewController.m
//  YeDian
//
//  Created by 罗西 on 3/29/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "searchPageViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "MyFansTableViewCell.h"
#import "UIButton+WebCache.h"
#import "MJRefresh.h"
#import "fujinYDTableViewCell.h"
#import "yedianxiangqingViewController.h"
#import <CoreLocation/CLLocation.h>
#import "PublishRecruitUI.h"
#import "zhaopinfabuViewController.h"
#import "zhaopinxiangqingViewController.h"
#import "qiuzhixiangqingViewController.h"

@interface searchPageViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>{
    NSDictionary *myInfoDic;
    NSInteger currentPage;
    NSArray *jobTitleData;
    NSString *job_title;
    UIButton *jobTypeBtn;
    NSString *key;
}

@property (nonatomic,strong) UITableView *mainTableView;
@property (nonatomic,strong) NSMutableArray *itemsArray;
@property (nonatomic,strong) UISegmentedControl *control;
@property (nonatomic,strong) UIButton *selectBgView;

@end

@implementation searchPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    UIBarButtonItem *btnBar = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    [rightBtn addTarget:self action:@selector(fabu) forControlEvents:UIControlEventTouchUpInside];
    //self.navigationItem.rightBarButtonItem = btnBar;
    
    self.title = @"搜索";
    jobTitleData=@[@"DJ",
                   @"灯光", @"mc", @"舞台总监", @"舞编", @"A组ds", @"B组ds", @"服务员", @"咨客",
                   @"营销", @"服务员领班", @"总经理", @"副总经理", @"楼面经理", @"企划", @"收银员",
                   @"收银员", @"保安",@"男歌手",@"女歌手", @"其他"];
    
    [self loadUI];
}

-(void)fabu{
    zhaopinfabuViewController *vc = [zhaopinfabuViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadUI{
    _control = [[UISegmentedControl alloc]initWithItems:@[@"夜店",@"招聘",@"求职"]];
    _control.frame = CGRectMake(-3, 0, SCREEN_WIDTH+6, 30);
    _control.tintColor = [UIColor redColor];
    _control.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_control];
    _control.selectedSegmentIndex = 0;
    
    [_control addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
    
    UIView *searchBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, 30)];
    searchBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:searchBgView];
    
    jobTypeBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    [jobTypeBtn setTitle:[NSString stringWithFormat:@"%@%@",@"职位",@"▼"] forState:UIControlStateNormal];
    [jobTypeBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    jobTypeBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    //[searchBgView addSubview:jobTypeBtn];
    [jobTypeBtn addTarget:self action:@selector(jobTypeSelete) forControlEvents:UIControlEventTouchUpInside];
    
    UISearchBar *jobSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(20, 5, SCREEN_WIDTH-40, 20)];
    jobSearchBar.placeholder = @"请输入职位";
    jobSearchBar.layer.borderColor = [UIColor lightGrayColor].CGColor;
    jobSearchBar.layer.borderWidth = 1.0f;
    //jobSearchBar.barTintColor = [UIColor clearColor];
    jobSearchBar.backgroundColor = [UIColor whiteColor];
    jobSearchBar.barTintColor = [UIColor whiteColor];
    [searchBgView addSubview:jobSearchBar];
    jobSearchBar.layer.masksToBounds = YES;
    jobSearchBar.layer.cornerRadius = 5.0f;
    jobSearchBar.delegate = self;
    
    UIView *sepView = [[UIView alloc]initWithFrame:CGRectMake(0, 29, SCREEN_WIDTH, 1)];
    sepView.backgroundColor = [UIColor lightGrayColor];
    [searchBgView addSubview:sepView];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, SCREEN_WIDTH, SCREEN_HEIGHT-64-60)];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //[self.mainTableView launchRefreshing];
    
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        currentPage = 0;
        [self loadData];
    }];
    
    self.mainTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        currentPage++;
        [self loadData];
    }];
    
    currentPage = 0;
    _itemsArray = [NSMutableArray new];
    
    //[self loadData];
    
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    key = searchBar.text;
    [self loadData];
}

-(void)jobTypeSelete{
    if (!_selectBgView) {
        _selectBgView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.view addSubview:_selectBgView];
        _selectBgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        [_selectBgView addTarget:self action:@selector(removeJobTypeBTN) forControlEvents:UIControlEventTouchUpInside];
        
        UIScrollView* sv=[[UIScrollView alloc] initWithFrame:CGRectMake(40,30, SCREEN_WIDTH-80 , SCREEN_HEIGHT-60)];
        sv.contentSize = CGSizeMake(SCREEN_WIDTH-80, 40*jobTitleData.count);
        sv.backgroundColor = [UIColor whiteColor];
        sv.showsHorizontalScrollIndicator = YES;
        sv.delegate = self;
        [_selectBgView addSubview:sv];
        
        for(int i=0;i<jobTitleData.count;i++){
            UIButton* btn=[[UIButton  alloc] initWithFrame:CGRectMake(0, 40*i, SCREEN_WIDTH-80, 40)];
            [btn addTarget:self action:@selector(selectTypeFn:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag=8000+i;
            [sv addSubview:btn];
            
            NSString*  str=jobTitleData[i];
            UILabel*  yzLb=[[UILabel alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH-80, 39.5)];
            yzLb.text=str;
            yzLb.textColor=[UIColor orangeColor];
            yzLb.font=[UIFont systemFontOfSize:13];
            yzLb.textAlignment=NSTextAlignmentCenter;
            [btn addSubview:yzLb];
            //
            UIImageView* line=[[UIImageView alloc] initWithFrame:CGRectMake(0,39.5, SCREEN_WIDTH-80, 0.5)];
            line.layer.backgroundColor=[[UIColor colorWithHexString:@"bfbfbf"] CGColor];
            [btn addSubview:line];
        }
    }
    
    
}

-(void)selectTypeFn:(UIButton*)btn{
    long tag=btn.tag-8000;
    job_title=jobTitleData[tag];
    [jobTypeBtn setTitle:[NSString stringWithFormat:@"%@%@",job_title,@"▼"] forState:UIControlStateNormal];
    if (_selectBgView) {
        [_selectBgView removeFromSuperview];
        _selectBgView = nil;
    }
    //[table reloadData];
    
    
}

-(void)removeJobTypeBTN{
    if (_selectBgView) {
        [_selectBgView removeFromSuperview];
        _selectBgView = nil;
    }
}

- (void) controllerPressed:(UISegmentedControl*)sender {
    currentPage = 0;
    _itemsArray = [NSMutableArray new];
    [self loadData];
    
    /* 添加代码,处理值的变化 */
}

-(void)loadData{
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"phone"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    
    loginURL=[loginURL stringByAppendingString:@"index.php/AppSearch/findPageList"];
    
    
    
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:[accountDefaults objectForKey:@"uid"] forKey:@"uid"];
    [req addPostValue:[NSString stringWithFormat:@"%ld",(long)currentPage] forKey:@"currentPage"];
    [req addPostValue:[NSString stringWithFormat:@"%ld",(long)_control.selectedSegmentIndex+1] forKey:@"searchtype"];
    [req addPostValue:[NSString stringWithFormat:@"%@",key] forKey:@"key"];
    
    [req startSynchronous];
    NSError *error = [req error];
    NSLog(@"保存URL.loginURL==%@",req.url);
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        NSString* uid=[myInfoDic objectForKey:@"uid"];
        NSLog(@"ID%@",uid);
        
        if (currentPage == 0) {
            _itemsArray = [NSMutableArray new];
        }
        
        [_itemsArray addObjectsFromArray:[myInfoDic objectForKey:@"resultList"]];
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        [self.mainTableView reloadData];
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}



#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _itemsArray.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    fujinYDTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[fujinYDTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    NSDictionary* dic = [_itemsArray objectAtIndex:indexPath.section];
    NSString *str_logo = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic1"]];
    if (_control.selectedSegmentIndex == 1) {
        str_logo = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"logo"]];
    }
    NSString *str_ = [dic objectForKey:@"logo"];
    if ([str_ isEqual:[NSNull null]]) {
        str_ = @"";
    }
    str_logo = str_;
    if ([str_logo rangeOfString:@"upload"].location != NSNotFound) {
        str_logo = [NSString stringWithFormat:@"%@%@",HOST,str_logo];
    }else{
        str_logo = [NSString stringWithFormat:@"%@/upload/%@",HOST,str_logo];
    }
    
    NSString *str_name = [dic objectForKey:@"title"];
    NSString *str_desc = [dic objectForKey:@"nickname"];
    if ([str_logo isEqual:[NSNull null]]) {
        str_logo = @"";
    }
    if ([str_name isEqual:[NSNull null]]) {
        str_name = @"";
    }
    if ([str_desc isEqual:[NSNull null]]) {
        str_desc = @"";
    }
    [cell.imgView setImageWithURL:[NSURL URLWithString:str_logo] forState:UIControlStateNormal];
    cell.nameLabel.text = str_name;
    cell.desLabel.text = str_desc;
    double lng;double lat;
    if (![[dic objectForKey:@"longi"] isEqual:[NSNull null]]) {
        lng = [[dic objectForKey:@"longi"]doubleValue];
    }
    if (![[dic objectForKey:@"lanti"] isEqual:[NSNull null]]) {
        lat = [[dic objectForKey:@"lanti"]doubleValue];
    }
    cell.disLabel.text = [self getDisByLng:lng lat:lat];
    cell.disLabel.text = [dic objectForKey:@"add_time"];
    
    return cell;
}

-(NSString *)getDisByLng:(double)lng lat:(double)lat{
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    
    
    NSString *_lng = [ud objectForKey:@"longitude"];
    NSString *_lat = [ud objectForKey:@"latitude"];
    if (_lng == nil) {
        _lng = @"0";
    }
    if (_lat == nil) {
        _lat = @"0";
    }
    
    double lng_ = [_lng doubleValue];
    double lat_ = [_lat doubleValue];
    
    CLLocation *orig=[[CLLocation alloc] initWithLatitude:lat  longitude:lng];
    CLLocation* dist=[[CLLocation alloc] initWithLatitude:lat_ longitude:lng_];
    
    CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;
    
    return [NSString stringWithFormat:@"%0.2f km",kilometers];
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_control.selectedSegmentIndex == 0) {
        NSUInteger row=[indexPath section];
        NSDictionary *dic=[_itemsArray objectAtIndex:row];
        NSString* merchant_id=[dic objectForKey:@"id"];
        yedianxiangqingViewController* ui=[[yedianxiangqingViewController alloc] init];
        ui.title = @"夜店详情";
        ui.merchantId=[merchant_id intValue];
        [self.navigationController pushViewController:ui animated:NO];
    }else if (_control.selectedSegmentIndex == 1){
        NSDictionary *dic=[_itemsArray objectAtIndex:indexPath.section];
        NSString* merchant_id=[dic objectForKey:@"id"];
        zhaopinxiangqingViewController* ui=[[zhaopinxiangqingViewController alloc] init];
        ui.merchantId=merchant_id;
        [self.navigationController pushViewController:ui animated:NO];
    }else if (_control.selectedSegmentIndex == 2){
        NSDictionary *dic=[_itemsArray objectAtIndex:indexPath.section];
        NSString* merchant_id=[dic objectForKey:@"id"];
        qiuzhixiangqingViewController* ui=[[qiuzhixiangqingViewController alloc] init];
        ui.merchantId=merchant_id;
        [self.navigationController pushViewController:ui animated:NO];
    }
    

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
